package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.CompanyAddrDao;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSetingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderSetingDao orderSetingDao;
    @Autowired
    MemberDao memberDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    CompanyAddrDao companyAddrDao;

    @Override
    public Result order(Map map) throws Exception {
          /*1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
            2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
            3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
            4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            5、预约成功，更新当日的已预约人数
            */
        Result result = null;
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = orderSetingDao.findOrderSettingByDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            //没有设置预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            Integer id = member.getId();
            Date order_Date = DateUtils.parseString2Date(orderDate);
            Integer setmealId = Integer.parseInt((String) map.get("setmealId"));
            Order order = new Order(id, order_Date, setmealId);
            //提交的数据在t_orderting是否有记录，有则是重复提交
            List<Order> orderList = orderDao.findByCondition(order);
            if (orderList != null && orderList.size() > 0) {
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        } else {
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setIdCard((String) map.get("idCard"));
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member.setSex((String) map.get("sex"));
            member.setName((String) map.get("name"));

            if(map.get("age")!=null){
            member.setAge(Integer.parseInt((String) map.get("age")));
            }

            if(map.get("maritalStatus")!=null){
                member.setMaritalStatus((String) map.get("maritalStatus"));
            }

            if(map.get("birthday")!=null){
                member.setBirthday(DateUtils.parseString2Date((String) map.get("birthday")));
            }
            memberDao.add(member);
        }
        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType((String) map.get("orderType"));

        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//中的(Integer) map.get("setmealId")转换不成功
        //Integer setmealId = (Integer) map.get("setmealId");

        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));
        //order.setSetmealId((Integer) map.get("setmealId"));

        order.setOrderStatus(Order.ORDERSTATUS);

        //6.将预约地址从map拿出
        String addressName = (String) map.get("addressName");
        if(addressName!=null){
            //phone
            Integer addrId = companyAddrDao.findIdByAddr(addressName);
            order.setCompanyAddressId(addrId);
        }else {
            //backend
            order.setCompanyAddressId((Integer) map.get("companyAddress"));
        }

        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSetingDao.editReservations(orderSetting);

        return new Result(true, MessageConstant.ORDER_SUCCESS, order);
    }
//回显订单成功信息
    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findOrderDetailById(id);
        if (map != null) {
            Date order_Date = (Date) map.get("orderDate");
            //日期转字符串
            String orderDate = DateUtils.parseDate2String(order_Date);
            map.put("orderDate", orderDate);
        }
        return map;
    }
//查询所有预约信息（分页，条件查询）
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<Order> page = orderDao.findOrderByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());

    }
//取消预约 删除预约信息
    @Override
    public void delete(Integer id) {
        orderDao.delete(id);
    }
//修改预约状态
    @Override
    public void update(Integer id) {
        Map map = new HashMap();
        map.put("id", id);
        map.put("orderStatus", Order.ORDERSTATUS_NO);
        orderDao.update(map);
    }
//返回地址列表
    @Override
    public List<Map> findAllAdr() {
        return orderDao.findAllAdr();
    }
}
